import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, AxiosInstance } from 'axios'
import { AJAX_TIMEOUT } from "@/config"
import { useUserStore } from '@/store/modules/user';
import { printStart } from '@/utils/print';
import { closeLoading } from '@/utils';
import { $alert, $message, $messageApi } from '../utils/tip';
import {showMessage} from "@/utils/hooks";
const baseURL: string = import.meta.env.VITE_BASE_URL
export interface IResult<T> {
  /** 响应码 */
  // code: 1 | "500" | "401" | 200 | 501,
  code: 1 | 500 | 401 | 200 | 501,
  /** 数据 */
  data?: T,
  /** 数据 */
  rows?: T,
  /** 额外的参数 */
  params?: any,
  /** 拼音码数组 */
  pym?: string[],
  /** 提示内容 */
  content?: string,
  /** 提示 */
  msg: string,
  /** 总条数 */
  total?: number
  /** 预交金额 */
  yjj?: string,
}

const service: AxiosInstance = axios.create({
  baseURL: baseURL,
  timeout: AJAX_TIMEOUT
})

// 请求前的统一处理
service.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 适配mock请求
    config.baseURL = config.url?.startsWith("/mock") ? "./" : config.baseURL;
    let plug = { html_href: window.location.href, html_hash: window.location.hash };
    if (typeof config.data !== 'undefined' && typeof config.data?.data !== 'undefined') {
      const userStore = useUserStore();
      config.data.data = { ...plug, cardInfo: userStore.cardInfo ?? {}, userInfo: userStore.user ?? {}, ...config.data.data }
    }
    if (typeof config.data !== 'undefined' && typeof config.data?.data === 'undefined') {
      const userStore = useUserStore();
      config.data = { ...plug, cardInfo: userStore.cardInfo ?? {}, userInfo: userStore.user ?? {}, ...config.data }
    }
    return config
  },
  (error: AxiosError) => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  async (response: AxiosResponse<IResult<any>>) => {
    const res = response;
    if (res.data.code === 1 || res.data.code === 200 || res.data.code === 501) {
      try {
        let res_data: any = res.data ?? {};
        if (res_data['notify_eval']) {
          var ef = eval(res_data['notify_eval']);
          if (typeof ef == 'function') {
            closeLoading();
            await ef();
          }
        }
      } catch (e) { }
      try {
        let res_data: any = res.data ?? {};
        if (res_data['notify_msg']) {
          closeLoading();

          await $alert({
            text: res_data['notify_msg'],
            type: res_data['notify_type'],
            durationSeconds: Number(res_data['notify_timeout'])
          });
        }
      } catch (e) { }
      try {
        let res_data: any = res.data.data ?? {};
        if (res_data['print_json']) {
          closeLoading();
          await printStart(res_data['print_json'])
        }
      } catch (e) { }
      return res;
    } else {
      try {
        let res_data: any = res.data ?? {};
        if (res_data['notify_msg']) {
          closeLoading();
          await $alert({
            text: res_data['notify_msg'],
            type: res_data['notify_type'],
            durationSeconds: Number(res_data['notify_timeout'])
          });
        }
      } catch (e) { }
      if (res.data.msg) {
        showMessage(res.data.msg, 'error',);

        //弹出提示框显示报错信息
        // showError(res.data.msg)
      }
      return Promise.reject(res)
      closeLoading();
    }
  },
  (error: AxiosError) => {
    console.log("bug:", error) // for debug
    const badMessage: any = error.message || error
    const code = parseInt(badMessage.toString().replace('Error: Request failed with status code ', ''))
    closeLoading();
    showError({ code, message: badMessage })
    return Promise.reject(error)
  }
)

// 错误处理
function showError(error: any) {
  closeLoading();
  $messageApi.error(error);
}


export default async  <T>(config: AxiosRequestConfig<any>): Promise<IResult<T>> => {
  return service(config).then(item => {
    return item.data;
  });
}
